package com.aiyige.page.webview;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.ExRouter;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiUrls;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.TokenManager;
import com.aiyige.base.eventbus.EventAddFollow;
import com.aiyige.base.eventbus.EventAgreement;
import com.aiyige.base.eventbus.EventBuySuccess;
import com.aiyige.base.eventbus.EventDeleteFollow;
import com.aiyige.base.eventbus.EventLogin;
import com.aiyige.base.eventbus.EventMomentChanged;
import com.aiyige.im.SessionHelper;
import com.aiyige.jpush.TagAliasOperatorHelper;
import com.aiyige.model.H5Banner;
import com.aiyige.model.TokenResponse;
import com.aiyige.model.User;
import com.aiyige.model.moment.backup.CommodityBackup;
import com.aiyige.model.moment.backup.CreatorBackup;
import com.aiyige.model.moment.backup.InventoryBackup;
import com.aiyige.model.moment.backup.MomentOnsaleBackup;
import com.aiyige.model.moment.backup.StatisticsBackup;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.my.message.util.MessageUtil;
import com.aiyige.page.photo.model.Photo;
import com.aiyige.page.photo.model.PhotoDetail;
import com.aiyige.page.player.PlayerInfo;
import com.aiyige.share.ShareDialog;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.exception.NeedLoginException;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.just.agentwebX5.AgentWebX5;
import com.just.agentwebX5.ChromeClientCallbackManager;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebStorage;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.vondear.rxtools.RxKeyboardTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.kevin.floatingeditor.EditorCallback;
import cn.kevin.floatingeditor.EditorHolder;
import cn.kevin.floatingeditor.FloatEditorActivity;
import okhttp3.ResponseBody;
import retrofit2.Response;


/**
 * Created by cenxiaozhong on 2017/5/23.
 */

@Route(path = ARouterConfig.WebViewPage)
public class WebViewPage extends BaseActivity {
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleFinishBtn)
    ImageView titleFinishBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.webviewContainer)
    FrameLayout webviewContainer;
    @BindView(R.id.loadingLayout)
    View loadingLayout;
    @BindView(R.id.titleBar)
    View titleBar;
    AgentWebX5 webview;
    @Autowired
    public String url;
    Handler mainHanlder;

    @Autowired
    public JSONObject headers;
    @Autowired
    public boolean disableNav = false;
    @Autowired
    public String fixedTitle;
    @Autowired
    public boolean noTitleBar = false;
    @BindView(R.id.titleShareBtn)
    ImageView titleShareBtn;
    boolean shareBtnShowed = false;

    public static void start(String url) {
        ARouter.getInstance().build(ARouterConfig.WebViewPage)
                .withString("url", url).navigation();
    }

    public void showShareBtn(boolean animated) {
        if (shareBtnShowed) return;
        shareBtnShowed = true;
        if (animated) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(titleShareBtn, "alpha", 0, 1);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    titleShareBtn.setVisibility(View.VISIBLE);
                }
            });
            animator.setDuration(300);
            animator.start();
        } else {
            titleShareBtn.setAlpha(1f);
            titleShareBtn.setVisibility(View.VISIBLE);
        }
    }


    public long autoConfigHideLoadingDelay() {
        if (url.contains(BuildConfig.PRIMARY_DOMAIN) && (url.contains(ExRouter.MAJOR_COURSE_DETAIL) || url.contains(ExRouter.ARTICLE_DETAIL))) {
            return 3000;
        } else {
            return 0;
        }
    }

    private void handleUrl() {
        try {
            if (TextUtils.isEmpty(url) || TextUtils.isEmpty(url.trim())) {
                throw new Exception("");
            }
            Uri uri = Uri.parse(url);
            Uri.Builder uriBuilder = uri.buildUpon();
            Set<String> existQueryParameters = uri.getQueryParameterNames();
            if (uri.toString().contains(BuildConfig.PRIMARY_DOMAIN)) {
                if (!existQueryParameters.contains("_client")) {
                    uriBuilder.appendQueryParameter("_client", "android");
                }
                if (!existQueryParameters.contains("_appversion")) {
                    uriBuilder.appendQueryParameter("_appversion", BuildConfig.appVersion);
                }
                if (!existQueryParameters.contains("token")) {
                    uriBuilder.appendQueryParameter("token", AccountUtil.getCurrentUser().getAccessToken().getAccess_token());
                }
                if (!existQueryParameters.contains("userId")) {
                    uriBuilder.appendQueryParameter("userId", AccountUtil.getCurrentUser().getIdUrlEncoded());
                }
            }
            url = uriBuilder.build().toString();
        } catch (Exception e) {
            url = "";
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_url);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setAutoRegisterEventBus(true);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        mainHanlder = new Handler(Looper.getMainLooper());
        handleUrl();
        if (TextUtils.isEmpty(url)) {
            ToastX.show(R.string.error_url);
            finish();
            return;
        }
        loadingLayout.setVisibility(View.VISIBLE);
        if (disableNav) {
            titleBackBtn.setImageResource(R.drawable.details_close);
        } else {
            titleBackBtn.setImageResource(R.drawable.sign_in_back);
        }
        titleBar.setVisibility(noTitleBar ? View.GONE : View.VISIBLE);
        initWebview();
        initJavaScriptObject();
        FloatEditorActivity.setDefaultValue(null);
    }


    private void initWebview() {
        AgentWebX5.CommonAgentBuilder builder = AgentWebX5.with(this)//
                .setAgentWebParent(webviewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))//
                .closeProgressBar()
                .setWebSettings(WebSettingsManager.getInstance())
                .setWebViewClient(createWebViewClient())
                .setWebChromeClient(createWebChromeClient())
                .setSecutityType(AgentWebX5.SecurityType.default_check);

        if (!TextUtils.isEmpty(fixedTitle)) {
            if (fixedTitle.length() > 10) {
                fixedTitle = fixedTitle.substring(0, 10);
            }
            titleTv.setVisibility(View.VISIBLE);
            titleTv.setText(fixedTitle);
        } else {
            builder.setReceivedTitleCallback(new ChromeClientCallbackManager.ReceivedTitleCallback() {
                @Override
                public void onReceivedTitle(WebView webView, String s) {
                    if (titleTv != null && !TextUtils.isEmpty(s))
                        if (s.length() > 10)
                            s = s.substring(0, 10) + "...";
                    titleTv.setVisibility(View.VISIBLE);
                    titleTv.setText(s);
                }
            });
        }

        if (headers != null) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                builder.additionalHttpHeader(entry.getKey(), entry.getValue().toString());
            }
        }

        webview = builder.createAgentWeb()//
                .ready()
                .go(url);
    }

    public void hideLoadingLayout() {
        loadingLayout.setVisibility(View.INVISIBLE);
    }

    private WebViewClient createWebViewClient() {
        return new WebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                mainHanlder.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        hideLoadingLayout();
                    }
                }, autoConfigHideLoadingDelay());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
                if (webResourceRequest.getUrl().toString().contains("h5.m.taobao.com/trade/paySuccess")) {
                    String response = "<!DOCTYPE html>\n" +
                            "<html lang=\"en\">\n" +
                            "<head>\n" +
                            "    <meta charset=\"UTF-8\">\n" +
                            "    <title>Title</title>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<script type=\"text/javascript\">\n" +
                            "    window.android && window.android.close();\n" +
                            "</script>\n" +
                            "</body>\n" +
                            "</html>";
                    WebResourceResponse webResourceResponse = new WebResourceResponse("text/html", "utf-8", new ByteArrayInputStream(response.getBytes(Charset.forName("UTF-8"))));
                    return webResourceResponse;
                } else {
                    return super.shouldInterceptRequest(webView, webResourceRequest);
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, String url) {
                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if (url.startsWith("alipays://platformapi/startApp?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if (url.startsWith(BuildConfig.AIYIGE_APP_SCHEME)) {
                    Router.start(url);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

        };
    }

    private WebChromeClient createWebChromeClient() {
        return new WebChromeClient();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        webview.uploadFileResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!disableNav) {
            if (webview.handleKeyEvent(keyCode, event)) {
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        WebStorage.getInstance().deleteAllData();
        webview.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    @OnClick({R.id.titleBackBtn, R.id.titleFinishBtn, R.id.titleShareBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleShareBtn:
                webview.getJsEntraceAccess().quickCallJs("requestShare");
                break;
            case R.id.titleBackBtn:
                if (disableNav || !webview.back()) {
                    finish();
                }
                break;
            case R.id.titleFinishBtn:
                finish();
                break;
        }
    }

    public class JavaScriptObject {
        //        @JavascriptInterface
//        public void share(String url, String title, String detail, String imageUrl) {
//            if (!TextUtils.isEmpty(url)) {
//                ShareUtil.getInstance().share(WebViewPage.this, url, title, detail, imageUrl);
//            } else {
//                ToastX.show(R.string.invalid_share_url);
//            }
//        }
        @JavascriptInterface
        public void showShare() {
            mainHanlder.post(new Runnable() {
                @Override
                public void run() {
                    showShareBtn(true);
                    hideLoadingLayout();
                }
            });
        }

        @JavascriptInterface
        public void nativeShare(String json) {
            try {
                JSONObject jsonObject = JSON.parseObject(json);
                String title = "";
                try {
                    title = jsonObject.getString("momentTitle");
                } catch (Exception e) {

                }
                String url = "";
                try {
                    url = jsonObject.getString("momentUrl");
                } catch (Exception e) {

                }
                String detail = "";
                try {
                    detail = jsonObject.getString("momentDetail");
                } catch (Exception e) {

                }
                String imageUrl = "";
                try {
                    imageUrl = jsonObject.getString("momentImg");
                } catch (Exception e) {

                }
                String creatorId = "";
                try {
                    creatorId = jsonObject.getString("momentCreator");
                } catch (Exception e) {

                }
                String subject = "";
                try {
                    subject = jsonObject.getString("momentSubject");
                } catch (Exception e) {

                }
                String momentId = "";
                try {
                    momentId = jsonObject.getString("momentId");
                } catch (Exception e) {

                }
                long viewCount = 0;
                try {
                    viewCount = jsonObject.getLong("momentViewCount");
                } catch (Exception e) {

                }
                long inventoryCount = 0;
                try {
                    inventoryCount = jsonObject.getLong("momentInventoryCount");
                } catch (Exception e) {

                }
                double price = 0;
                try {
                    price = jsonObject.getDouble("momentPrice");
                } catch (Exception e) {

                }

                Double momentOnSalePrice = null;
                try {
                    if (jsonObject.containsKey("momentOnSalePrice")) {
                        momentOnSalePrice = jsonObject.getDouble("momentOnSalePrice");
                    }
                } catch (Exception e) {
                    momentOnSalePrice = null;
                }

                Moment moment = new Moment();
                moment.setTitle(title);
                moment.setWebUrl(url);
                moment.setRouter(url);
                moment.setSummary(detail);
                moment.setCover(Arrays.asList(imageUrl));
                moment.setCreator(creatorId);
                CommodityBackup commodityBackup = new CommodityBackup();
                commodityBackup.setPrice(price);
                commodityBackup.setOriginPrice(price);
                commodityBackup.setUnitPrice(price);
                moment.setCommodityBackup(commodityBackup);
                InventoryBackup inventoryBackup = new InventoryBackup();
                inventoryBackup.setAvailableInventory(inventoryCount);
                moment.setInventoryBackup(inventoryBackup);
                CreatorBackup creatorBackup = new CreatorBackup();
                creatorBackup.setId(creatorId);
                moment.setCreatorBackup(creatorBackup);
                moment.setSubject(subject);
                moment.setId(momentId);
                StatisticsBackup statisticsBackup = new StatisticsBackup();
                statisticsBackup.setViewCount(viewCount);
                moment.setStatisticsBackup(statisticsBackup);
                if (momentOnSalePrice == null) {
                    moment.setOnSalesBackup(new MomentOnsaleBackup());
                } else {
                    MomentOnsaleBackup momentOnsaleBackup = new MomentOnsaleBackup();
                    momentOnsaleBackup.setEndTime(0l);
                    momentOnsaleBackup.setStartTime(0l);
                    momentOnsaleBackup.setPrice(momentOnSalePrice);
                    moment.setOnSalesBackup(momentOnsaleBackup);
                }
                ShareDialog.newInstance(WebViewPage.this)
                        .shareMoment(new Moment(moment));
            } catch (Exception e) {
                ToastX.show(e);
            }
        }

        @JavascriptInterface
        public void hideLoading() {
            mainHanlder.post(new Runnable() {
                @Override
                public void run() {
                    hideLoadingLayout();
                }
            });
        }

        @JavascriptInterface
        public void nativeChat(String accid) {
            if (TextUtils.isEmpty(accid)) return;
            try {
                SessionHelper.startP2PSession(WebViewPage.this, accid);
            } catch (Exception e) {
            }
        }

        @JavascriptInterface
        public String clientType() {
            return "android";
        }

        @JavascriptInterface
        public void close() {
            finish();
        }

        @JavascriptInterface
        public void requestLogin() {
            if (AccountUtil.isLogin()) {
                onEventLogin(null);
            } else {
                ARouter.getInstance()
                        .build(ARouterConfig.LoginPage)
                        .navigation();
            }
        }

        @JavascriptInterface
        public void refreshToken() {
            new RefreshTokenTask(WebViewPage.this).execute();
        }


        @JavascriptInterface
        public void forceLogin() {
            ARouter.getInstance()
                    .build(ARouterConfig.LoginPage)
                    .navigation();
        }

        @JavascriptInterface
        public void closePage() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!webview.back()) {
                        finish();
                    }
                }
            });
        }

        @JavascriptInterface
        public String getOSType() {
            return "android";
        }

        @JavascriptInterface
        public void buy(String momentId, String subject, int buyNum) {
            ARouter.getInstance()
                    .build(ARouterConfig.ConfirmOrderPage)
                    .withString("goodsId", momentId)
                    .withString("source", "app")
                    .withString("sourceUrl", ApiUrls.BaseUrl)
                    .withInt("buyNum", buyNum)
                    .withBoolean("multiBuy", true)
                    .navigation();
        }


        @JavascriptInterface
        public void buy(String momentId, String subject, int buyNum, String tid, int code) {
            ARouter.getInstance()
                    .build(ARouterConfig.ConfirmOrderPage)
                    .withString("goodsId", momentId)
                    .withString("source", "app")
                    .withString("sourceUrl", ApiUrls.BaseUrl)
                    .withInt("buyNum", buyNum)
                    .withBoolean("multiBuy", true)
                    .withBoolean("fromH5", true)
                    .withString("h5Tid", tid)
                    .withInt("h5Code", code)
                    .navigation();
        }

        @JavascriptInterface
        public String getUserInfo() {
            if (AccountUtil.isLogin()) {
                Map<String, String> map = new HashMap<>();
                map.put("userId", AccountUtil.getCurrentUser().getId());
                map.put("token", AccountUtil.getCurrentUser().getAccessToken().getAccess_token());
                return JSON.toJSONString(map);
            } else {
                Map<String, String> map = new HashMap<>();
                map.put("userId", "");
                map.put("token", "");
                return JSON.toJSONString(map);
            }
        }

        @JavascriptInterface
        public void fullScreen(String url, String type) {
            if (TextUtils.isEmpty(url) || TextUtils.isEmpty(type)) {
                return;
            }
            if (type.equals("video")) {
                List<PlayerInfo> playList = new ArrayList<>();
                playList.add(PlayerInfo.newBuilder()
                        .cover("")
                        .isFree(true)
                        .path(url)
                        .title("")
                        .build());
                ARouter.getInstance()
                        .build(ARouterConfig.PlayerPage)
                        .withSerializable("playList", (Serializable) playList)
                        .navigation();
            } else if (type.equals("photo")) {
                List<Photo> photoList = new LinkedList<>();
                photoList.add(Photo.newBuilder()
                        .url(url)
                        .introduction("")
                        .build());
                PhotoDetail photoDetail = PhotoDetail.newBuilder()
                        .goodsId("")
                        .localPhoto(false)
                        .photoList(photoList)
                        .title("")
                        .build();
                ARouter.getInstance()
                        .build(ARouterConfig.PhotoPage)
                        .withParcelable("photoDetail", photoDetail)
                        .navigation();
            }
        }


        @JavascriptInterface
        public void showBanner(String json, int index) {
            try {
                List<H5Banner> h5BannerList = JSON.parseArray(json, H5Banner.class);
                if (ListUtil.isEmpty(h5BannerList)) {
                    throw new Exception();
                }
                List<Photo> photoList = new LinkedList<>();
                outLoop:
                for (H5Banner h5Banner : h5BannerList) {
                    int mediaType;
                    switch (h5Banner.getMediaType()) {
                        case H5Banner.MEDIA_TYPE_PHOTO:
                            mediaType = Photo.MEDIA_TYPE_PHOTO;
                            break;
                        case H5Banner.MEDIA_TYPE_VIDEO:
                            mediaType = Photo.MEDIA_TYPE_VIDEO;
                            break;
                        default:
                            continue outLoop;
                    }
                    photoList.add(Photo.newBuilder()
                            .url(h5Banner.getUrl())
                            .videoUrl(h5Banner.getVideoUrl())
                            .mediaType(mediaType)
                            .introduction("")
                            .build());
                }
                if (ListUtil.isEmpty(photoList)) {
                    throw new Exception();
                }
                PhotoDetail photoDetail = PhotoDetail.newBuilder()
                        .goodsId("")
                        .localPhoto(false)
                        .photoList(photoList)
                        .title("")
                        .playIndex(index)
                        .build();
                ARouter.getInstance()
                        .build(ARouterConfig.PhotoPage)
                        .withParcelable("photoDetail", photoDetail)
                        .navigation();
            } catch (Exception e) {


            }
        }


        @JavascriptInterface
        public void showCommentDialog(String hintValue, String commentId) {
            commentDialog(hintValue, commentId);
        }

        /**
         * 同意协议
         * @param agree
         */
        @JavascriptInterface
        public void agreement(boolean agree) {
            EventBus.getDefault().post(EventAgreement.newBuilder().agree(agree).build());
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventLogin(EventLogin event) {
        Map<String, String> map = new HashMap<>();
        map.put("userID", AccountUtil.getCurrentUser().getId());
        map.put("token", AccountUtil.getCurrentUser().getAccessToken().getAccess_token());
        webview.getJsEntraceAccess().quickCallJs("fetchToken", JSON.toJSONString(map));
    }

    /**
     * 商品发生了变化
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayChanged(EventMomentChanged event) {
        if (webview != null) {
            webview.getJsEntraceAccess().quickCallJs("reloadDetail");
        }
    }

    /**
     * 处理关注
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventAddFollow event) {
        if (webview != null) {
            webview.getJsEntraceAccess().quickCallJs("reloadDetail");
        }
    }

    /**
     * 处理取消关注
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventDeleteFollow event) {
        if (webview != null) {
            webview.getJsEntraceAccess().quickCallJs("reloadDetail");
        }
    }

    /**
     * 购买成功
     *
     * @param eventBuySuccess
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessEventBuss(EventBuySuccess eventBuySuccess) {
        if (webview != null) {
            webview.getJsEntraceAccess().quickCallJs("reloadDetail");
        }
    }

    public void initJavaScriptObject() {
        webview.getJsInterfaceHolder().addJavaObject("android", new JavaScriptObject());
    }

    @Override
    protected void onResume() {
        super.onResume();
        webview.getWebLifeCycle().onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        webview.getWebLifeCycle().onPause();
    }

    private void commentDialog(String hintValue, final String commentId) {
        FloatEditorActivity.openEditor(WebViewPage.this, new EditorCallback() {
                    @Override
                    public void onCancel(String content) {
                        FloatEditorActivity.setDefaultValue(content);
                        RxKeyboardTool.hideSoftInput(WebViewPage.this);
                    }

                    @Override
                    public void onSubmit(String content) {
                        webview.getJsEntraceAccess().quickCallJs("submitComment", content, commentId);
                        FloatEditorActivity.setDefaultValue(null);
                    }

                    @Override
                    public void onAttached(ViewGroup rootView) {


                    }
                },
                new EditorHolder(R.layout.fast_reply_floating_layout,
                        R.id.tv_cancel, R.id.tv_submit, R.id.et_content), hintValue, new InputFilter[]{new InputNumFilter(200, true)});
    }

    public class RefreshTokenTask extends SafeAsyncTask<Object, Object, Object> {

        public RefreshTokenTask(Activity activity) {
            super(activity, R.string.loading);
        }


        @Override
        protected Object doInBackground(Object... objects) {
            try {
                String clientInfo = Base64.encodeToString((BuildConfig.AIYIGE_CLIENT_ID + ":" + BuildConfig.AIYIGE_CLIENT_SECRET).getBytes("UTF-8"), Base64.NO_WRAP | Base64.URL_SAFE);
                Response<ResponseBody> refreshTokenResp = TokenManager.getService().refreshToken("Basic " + clientInfo, "refresh_token", AccountUtil.getCurrentUser().getAccessToken().getRefresh_token()).execute();
                if (refreshTokenResp.code() == ResponseCode.UNAUTHORIZED) {
                    AccountUtil.clearCurrentUser();
                    MessageUtil.clearNewMessage();
                    TagAliasOperatorHelper.getInstance().cleanLoginTagAndAlias(MyApp.getAppContext());
                    ARouter.getInstance().build(ARouterConfig.LoginPage).navigation();
                    throw new NeedLoginException(StringUtils.getString(R.string.please_login));
                } else if (refreshTokenResp.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(refreshTokenResp));
                }
                String refreshTokenJson = RetrofitUtil.getResponseBodyAsString(refreshTokenResp);
                TokenResponse tokenResponse = JSON.parseObject(refreshTokenJson, TokenResponse.class);
                User user = AccountUtil.getCurrentUser();
                user.getAccessToken().setAccess_token(tokenResponse.getAccess_token());
                user.getAccessToken().setRefresh_token(tokenResponse.getRefresh_token());
                user.getAccessToken().setToken_type(tokenResponse.getToken_type());
                user.getAccessToken().setExpires_in(tokenResponse.getExpires_in());
                AccountUtil.updateCurrentUser(user);
                return null;
            } catch (Exception e) {
                return e;
            }
        }


        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                onEventLogin(null);
            }
        }
    }

}
